<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">用户登录</h2>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" @keyup.enter="handleLogin">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="用户名" clearable autofocus />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="密码" clearable show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width:100%" :loading="loading" @click="handleLogin">登录</el-button>
        </el-form-item>
      </el-form>
      <div class="login-footer">
        <span>还没有账号？</span>
        <el-link type="primary" @click="goRegister">去注册</el-link>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import request from '@/utils/request';
import { ElMessage } from 'element-plus';

const router = useRouter();
const userStore = useUserStore();

const loginForm = ref({ username: '', password: '' });
const loading = ref(false);
const loginFormRef = ref(null);

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
};

const handleLogin = async () => {
  await loginFormRef.value?.validate();
  loading.value = true;
  try {
    const response = await request.post('/user/login', {
      username: loginForm.value.username,
      password: loginForm.value.password
    });
    if (response.code === 200) {
      userStore.setUserId(response.data.id);
      userStore.setUserInfo({
        id: response.data.id,
        username: response.data.username,
        role: response.data.role
      });
      ElMessage.success('登录成功');
      router.push('/products');
    } else {
      ElMessage.error(response.message || '登录失败');
    }
  } catch (error) {
    ElMessage.error('登录失败: ' + (error.response?.data?.message || '网络错误'));
  } finally {
    loading.value = false;
  }
};

const goRegister = () => {
  router.push('/register');
};
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
}
.login-card {
  width: 350px;
  padding: 32px 24px 18px 24px;
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.08);
}
.login-title {
  text-align: center;
  margin-bottom: 24px;
  color: #409eff;
  font-weight: 600;
  font-size: 22px;
  letter-spacing: 2px;
}
.login-footer {
  margin-top: 18px;
  text-align: center;
  color: #888;
  font-size: 14px;
}
</style>